/*
package com.huaxin.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaxin.api.feign.RemoteGradeService;
import com.huaxin.api.feign.RemoteLoginService;
import com.huaxin.api.feign.RemoteOrganizationService;
import com.huaxin.api.model.dto.EpUserInfo;
import com.huaxin.api.model.entity.EpOrganization;
import com.huaxin.api.model.entity.WpOaTeam;
import com.huaxin.common.core.constant.SecurityConstants;
import com.huaxin.common.core.model.R;
import com.huaxin.common.security.exception.ServerErrorException;
import com.huaxin.em.api.model.dto.MaintenancePlanDto;
import com.huaxin.em.api.model.dto.MaintenancePlanYearDto;
import com.huaxin.em.api.model.entity.*;
import com.huaxin.em.api.model.vo.*;
import com.huaxin.em.constant.MaintenancePlanConstant;
import com.huaxin.em.dao.*;
import com.huaxin.em.service.EpEmEquipmentPositionService;
import com.huaxin.em.service.EpEmEquipmentService;
import com.huaxin.em.service.EpEmMaintenancePlanService;
import com.huaxin.em.service.EpEmMaintenanceService;
import com.huaxin.em.utils.DateUtil;
import com.huaxin.em.utils.PointPoiUtil;
import com.huaxin.pm.api.feign.RemoteEpPmCatalogueService;
import com.huaxin.pm.api.model.dto.EpPmCatalogueDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

*
 * 维护计划 service 层
 *
 * @author lyc
 * @Date 2020年12月22日15:13:33


@Slf4j
@Transactional(rollbackFor = {Exception.class, RuntimeException.class})
@Service
public class EpEmMaintenancePlanServiceImpl extends ServiceImpl<EpEmMaintenancePorjectDao, EpEmMaintenancePorject> implements EpEmMaintenancePlanService {

    @Autowired
    private EpEmMaintenanceContentDao epEmMaintenanceContentDao;


    @Autowired
    private EpEmMaintenanceEquipmentDao epEmMaintenanceEquipmentDao;

    @Autowired
    private EpEmMaintenancePlanDao epEmMaintenancePlanDao;


    @Autowired
    private EpEmMaintenanceRecordDao epEmMaintenanceRecordDao;

    @Autowired
    private EpEmMaintenanceRecordFileDao epEmMaintenanceRecordFileDao;


    @Autowired
    private EpEmMaintenanceCostDao epEmMaintenanceCostDao;

    @Autowired
    private EpEmMaintenanceService epEmMaintenanceService;

*
     * 物料信息


    @Autowired
    private RemoteEpPmCatalogueService catalogueService;

*
     * 组织 / 部门 Feign


    @Autowired
    private RemoteOrganizationService organizationService;


*
     * 组织 / 部门 Feign


    @Autowired
    private RemoteGradeService remoteGradeService;


    @Autowired
    private EpEmEquipmentService epEmEquipmentService;


    @Autowired
    private EpEmEquipmentDao epEmEquipmentDao;

*
     * 查询企业设施


    @Autowired
    private EpEmEquipmentPositionService epEmEquipmentPositionService;

*
     * 人员


    @Autowired
    private RemoteLoginService remoteLoginService;


*
     * 分页查询
     *
     * @param query 查询
     * @return IPage
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public IPage queryPage(EpEmMaintenancePorjectPageVO query) {
        IPage iPage = switchQuery(query);
        List<EpEmMaintenancePorject> rows = iPage.getRecords();
        if (rows == null || rows.isEmpty())
            return iPage;
        List<EpEmMaintenancePorjectVO> records = rows.stream().map(item -> {
            EpEmMaintenancePorjectVO vo = new EpEmMaintenancePorjectVO();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());
        List<Integer> Ids = new ArrayList<>(); //维护项目Id集合
        records.forEach(item -> Ids.add(item.getProjectId()));

        List<EpEmMaintenanceContent> contents = getContentsByProjectIds(Ids);
        List<EpEmMaintenanceEquipment> equipments = getEquipmentsByProjectIds(Ids);

        Map<Integer, List<EpEmMaintenanceContent>> contentMap = new HashMap<>();
        Set<String> userIds = new HashSet<>();
        contents.forEach(item -> {
            Integer projectId = item.getProjectId();
            if (contentMap.containsKey(projectId)) {
                contentMap.get(projectId).add(item);
            } else {
                contentMap.put(projectId, new ArrayList<>(Collections.singletonList(item)));
            }
            String userId = item.getUserId();
            if (StringUtils.isNoneBlank(userId)) //维护人员
                userIds.addAll(Arrays.asList(userId.split(MaintenancePlanConstant.STR_SPLIT)));
            if (item.getPublisherId() != null)//派工人员
                userIds.add(String.valueOf(item.getPublisherId()));
        });
        //查询用户信息
        Map<String, String> userMap = this.getUsersByIds(String.join(MaintenancePlanConstant.STR_SPLIT, userIds));

        Map<Integer, List<EpEmMaintenanceEquipment>> equipmentMap = new HashMap<>();
        equipments.forEach(item -> {
            Integer projectId = item.getProjectId();
            if (equipmentMap.containsKey(projectId)) {
                equipmentMap.get(projectId).add(item);
            } else {
                equipmentMap.put(projectId, new ArrayList<>(Collections.singletonList(item)));
            }
        });
        records.forEach(item -> {
            Integer projectId = item.getProjectId();
            int eqSize = equipmentMap.getOrDefault(projectId, new ArrayList<>()).size(); //设备台数
            if (eqSize != 0)
                item.setEquipmentCount(eqSize);
            if (contentMap.containsKey(projectId)) {
                List<EpEmMaintenanceContent> contentList = contentMap.get(projectId);
                Set<Integer> depts = new HashSet<>(); //统计部门
                AtomicReference<BigDecimal> hours = new AtomicReference<>(BigDecimal.ZERO); //工时估算
                AtomicReference<BigDecimal> costs = new AtomicReference<>(BigDecimal.ZERO); //成本估算
                Set<String> tmpWhUsers = new LinkedHashSet<>(); //维护人员
                Set<String> tmpDpUsers = new LinkedHashSet<>(); //派工人员
                contentList.forEach(san -> {
                    depts.add(san.getDepartmentId());
                    BigDecimal hourEstimate = BigDecimal.valueOf(san.getHourEstimate() == null ? 0d : san.getHourEstimate());
                    hours.set(hours.get().add(hourEstimate.multiply(BigDecimal.valueOf(eqSize))));
                    BigDecimal costEstimate = BigDecimal.valueOf(san.getCostEstimate() == null ? 0d : san.getCostEstimate());
                    costs.set(costs.get().add(costEstimate.multiply(BigDecimal.valueOf(eqSize))));

                    String userId = san.getUserId();
                    if (StringUtils.isNoneBlank(userId)) //维护人员
                        tmpWhUsers.addAll(Arrays.asList(userId.split(MaintenancePlanConstant.STR_SPLIT)));
                    if (san.getPublisherId() != null)//派工人员
                        tmpDpUsers.add(String.valueOf(san.getPublisherId()));
                });
                item.setContentCount(contentList.size());
                item.setDeptCount(depts.size());
                item.setHourCount(hours.get());
                item.setCostCount(costs.get());
                item.setMaintainUsers(boxUserNames(userMap, tmpWhUsers));
                item.setDispatchUser(boxUserNames(userMap, tmpDpUsers));
            }
        });
        iPage.setRecords(records);
        return iPage;
    }

*
     * 分页查询数据
     *
     * @param query 查询条件
     * @return R
     * @date 2020年12月22日15:17:34
     * @author lyc


    private IPage switchQuery(EpEmMaintenancePorjectPageVO query) {
        query = query == null ? new EpEmMaintenancePorjectPageVO() : query;
        if (query.getYear() == null) {
            query.setYear(LocalDate.now().getYear());
        }
        Page page = new Page();
        BeanUtils.copyProperties(query, page);
        String maintenanceTeam = query.getMaintenanceTeam();
        if (StringUtils.isNoneBlank(maintenanceTeam)) {
            List<String> teamIds = new ArrayList<>(Arrays.asList(maintenanceTeam.split(MaintenancePlanConstant.STR_SPLIT)));
            maintenanceTeam = teamIds.stream().map(teamId -> "^" + teamId + "$|," + teamId + "|" + teamId + ",|," + teamId + ",")
                    .collect(Collectors.joining("|"));
            query.setMaintenanceTeam(maintenanceTeam);
        }
        String equipmentNum = query.getEquipmentNum();
        if (StringUtils.isNoneBlank(equipmentNum)) {
            query.setEquipmentNum(null);
            LambdaQueryWrapper<EpEmEquipment> equipmenQueryWrapper = new LambdaQueryWrapper<>();
            List<String> equipmentNums = Arrays.asList(equipmentNum.split(MaintenancePlanConstant.STR_SPLIT));
            equipmenQueryWrapper.in(EpEmEquipment::getEquipmentNum, equipmentNums);
            List<EpEmEquipment> epEmEquipments = epEmEquipmentDao.selectList(equipmenQueryWrapper);
            if (epEmEquipments != null && !epEmEquipments.isEmpty()) {
                String equipmentIds = epEmEquipments.stream().map(e -> String.valueOf(e.getEquipmentId())).collect(Collectors.joining(MaintenancePlanConstant.STR_SPLIT));
                query.setEquipmentNum(StringUtils.isNoneBlank(equipmentIds) ? equipmentIds : null); //将Id赋值
            }
        }
        IPage iPage = this.baseMapper.queryPage(page, query);
        return iPage;
    }


*
     * 条件查询
     *
     * @param query 查询条件
     * @return R
     * @date 2020年12月22日15:17:34
     * @author lyc


    private List<EpEmMaintenanceContent> selectByQuery(EpEmMaintenancePorjectExportVO query) {
        query = query == null ? new EpEmMaintenancePorjectExportVO() : query;
        if (query.getYear() == null) {
            query.setYear(LocalDate.now().getYear());
        }
        String maintenanceTeam = query.getMaintenanceTeam();
        if (StringUtils.isNoneBlank(maintenanceTeam)) {
            List<String> teamIds = new ArrayList<>(Arrays.asList(maintenanceTeam.split(MaintenancePlanConstant.STR_SPLIT)));
            maintenanceTeam = teamIds.stream().map(teamId -> "^" + teamId + "$|," + teamId + "|" + teamId + ",|," + teamId + ",")
                    .collect(Collectors.joining("|"));
            query.setMaintenanceTeam(maintenanceTeam);
        }
        String equipmentNum = query.getEquipmentNum();
        if (StringUtils.isNoneBlank(equipmentNum)) {
            query.setEquipmentNum(null);
            LambdaQueryWrapper<EpEmEquipment> equipmenQueryWrapper = new LambdaQueryWrapper<>();
            List<String> equipmentNums = Arrays.asList(equipmentNum.split(MaintenancePlanConstant.STR_SPLIT));
            equipmenQueryWrapper.in(EpEmEquipment::getEquipmentNum, equipmentNums);
            List<EpEmEquipment> epEmEquipments = epEmEquipmentDao.selectList(equipmenQueryWrapper);
            if (epEmEquipments != null && !epEmEquipments.isEmpty()) {
                String equipmentIds = epEmEquipments.stream().map(e -> String.valueOf(e.getEquipmentId())).collect(Collectors.joining(MaintenancePlanConstant.STR_SPLIT));
                query.setEquipmentNum(StringUtils.isNoneBlank(equipmentIds) ? equipmentIds : null); //将Id赋值
            }
        }
        List<EpEmMaintenanceContent> contents = this.baseMapper.selectByQuery(query);
        return contents == null || contents.isEmpty() ? new ArrayList<>() : contents;
    }


*
     * 添加
     *
     * @param bean 添加的数据
     * @return R
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public MaintenancePlanDto add(MaintenancePlanDto bean) {
        check(bean, Boolean.FALSE);
        // 维护计划-项目 新增
        EpEmMaintenancePorject project = bean.getProject();
        this.save(project);
        Integer projectId = project.getProjectId();
        // 维护计划-内容 新增
        List<EpEmMaintenanceContent> contents = bean.getContents();
        contents.forEach(item -> {
            item.setProjectId(projectId);
            epEmMaintenanceContentDao.insert(item);
            List<EpEmMaintenancePlan> plans = this.doHandlePlan(item);
            plans.forEach(plan -> epEmMaintenancePlanDao.insert(plan));
        });
        // 维护计划-设备 新增
        List<EpEmMaintenanceEquipment> equipments = bean.getEquipments();
        equipments.forEach(item -> {
            item.setProjectId(projectId);
            epEmMaintenanceEquipmentDao.insert(item);
        });
        return bean;
    }

*
     * 获取用户信息
     *
     * @param userMap  用户map
     * @param elements 用户Ids
     * @return Map<Integer, String>
     * @date 2020年12月22日15:17:34
     * @author lyc


    public String boxUserNames(Map<String, String> userMap, Set<String> elements) {
        return elements.stream().filter(userMap::containsKey).map(userMap::get).collect(Collectors.joining(MaintenancePlanConstant.STR_SPLIT));
    }

*
     * 获取用户信息
     *
     * @param userIds 用户Ids
     * @return Map<Integer, String>
     * @date 2020年12月22日15:17:34
     * @author lyc


    public Map<String, String> getUsersByIds(String userIds) {
        Map<String, String> UserMap = new HashMap<>();
        try {
            List<EpUserInfo> users = remoteLoginService.selectByUserIds(userIds, SecurityConstants.FROM_IN);
            UserMap = users.stream()
                    .collect(Collectors.toMap(e -> String.valueOf(e.getUserId()), EpUserInfo::getUserName));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return UserMap;
    }


*
     * 获取用户信息
     *
     * @param deptIds 部门IDs
     * @return Map<Integer, String>
     * @date 2020年12月22日15:17:34
     * @author lyc


    public Map<Integer, List<EpUserInfo>> getDeptByIds(Set<Integer> deptIds) {
        Map<Integer, List<EpUserInfo>> UserMap = new HashMap<>();
        if (deptIds == null || deptIds.isEmpty())
            return UserMap;
        deptIds.forEach(deptId -> {
            try {
                List<EpUserInfo> users = remoteLoginService.findDepartmentId(deptId, SecurityConstants.FROM_IN);
                if (users != null && !users.isEmpty()) {
                    UserMap.put(deptId, users);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        });
        return UserMap;
    }


*
     * 修改
     *
     * @param bean 修改的数据
     * @return R
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public MaintenancePlanDto upd(MaintenancePlanDto bean) {
        check(bean, Boolean.TRUE);
        // 维护计划-项目 修改
        EpEmMaintenancePorject project = bean.getProject();
        this.updateById(project);
        Integer projectId = project.getProjectId(); // 维护项目Id
        // 维护计划-内容 修改
        this.doHandleContent(projectId, bean.getContents());
        // 维护计划-设备 修改
        this.doHandleEquipment(projectId, bean.getEquipments());
        return bean;
    }

*
     * 维护计划-内容 修改
     *
     * @param projectId 维护计划主键
     * @param contents  维护内容集合
     * @date 2020-12-23 09:22:03
     * @author lyc


    private void doHandleContent(Integer projectId, List<EpEmMaintenanceContent> contents) {
        List<EpEmMaintenanceContent> dbs = this.getContentsByProjectId(projectId);
        //前端传递过来的Id集合
        Set<Integer> Ids = new HashSet<>();
        contents.forEach(item -> Ids.add(item.getProjectId()));
        //需要删除的Id 集合
        Set<Integer> delIds = new HashSet<>();
        dbs.forEach(item -> {
            if (!Ids.contains(item.getProjectId()))
                delIds.add(item.getProjectId());
        });
        List<EpEmMaintenancePlan> plans = new ArrayList<>();
        List<Integer> delContentIds = new ArrayList<>();
        //处理 新增和修改的数据
        contents.forEach(item -> {
            Integer id = item.getProjectId();
            Integer contentId = item.getContentId();
            if (id != null) { //更新
                epEmMaintenanceContentDao.updateById(item);
            } else { //新增
                epEmMaintenanceContentDao.insert(item);
            }
            delContentIds.add(contentId);
            plans.addAll(this.doHandlePlan(item));
        });
        //处理需要删除的数据
        epEmMaintenanceContentDao.deleteBatchIds(delIds);
        //维护计划删除
        LambdaUpdateWrapper<EpEmMaintenancePlan> equipmentDel = new LambdaUpdateWrapper<>();
        equipmentDel.in(EpEmMaintenancePlan::getContentId, delContentIds);
        epEmMaintenancePlanDao.delete(equipmentDel);
        //新增计划
        plans.forEach(plan -> epEmMaintenancePlanDao.insert(plan));
    }

*
     * 维护计划-设备 修改
     *
     * @param projectId  维护计划主键
     * @param equipments 维护设备集合
     * @date 2020-12-23 09:22:03
     * @author lyc


    private void doHandleEquipment(Integer projectId, List<EpEmMaintenanceEquipment> equipments) {
        List<EpEmMaintenanceEquipment> dbs = this.getEquipmentsByProjectId(projectId);
        //前端传递过来的Id集合
        Set<Integer> Ids = new HashSet<>();
        equipments.forEach(item -> Ids.add(item.getProjectId()));
        //需要删除的Id 集合
        Set<Integer> delIds = new HashSet<>();
        dbs.forEach(item -> {
            if (!Ids.contains(item.getProjectId()))
                delIds.add(item.getProjectId());
        });
        //处理 新增和修改的数据
        equipments.forEach(item -> {
            Integer id = item.getProjectId();
            if (id != null) { //更新
                epEmMaintenanceEquipmentDao.updateById(item);
            } else { //新增
                epEmMaintenanceEquipmentDao.insert(item);
            }
        });
        //处理需要删除的数据
        epEmMaintenanceEquipmentDao.deleteBatchIds(delIds);
    }


*
     * 删除
     *
     * @param projectIdStrs 维护计划删除
     * @return boolean
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public boolean del(String projectIdStrs) {
        try {
            if (projectIdStrs == null || "".equals(projectIdStrs))
                throw new Exception("ID不能为空");
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }
        String[] split = projectIdStrs.split(MaintenancePlanConstant.STR_SPLIT);
        List<Integer> projectIds = new ArrayList<>(Arrays.asList(split)).stream().map(Integer::parseInt).collect(Collectors.toList());

        //查询出计划数据
        List<EpEmMaintenanceContent> contents = getContentsByProjectIds(projectIds);
        //维护项目删除
        this.removeByIds(projectIds);
        if (contents != null && !contents.isEmpty()) {
            //内容Ids
            List<Integer> contentIds = contents.stream().map(EpEmMaintenanceContent::getContentId).collect(Collectors.toList());
            //维护内容删除
            delContent(contentIds);
        }

        //维护设备删除
        LambdaUpdateWrapper<EpEmMaintenanceEquipment> equipmentDel = new LambdaUpdateWrapper<>();
        equipmentDel.in(EpEmMaintenanceEquipment::getProjectId, projectIds);
        epEmMaintenanceEquipmentDao.delete(equipmentDel);
        return true;
    }

*
     * 查询单条数据
     *
     * @param id 维护计划Id
     * @return MaintenancePlanDto
     * @date 2020年12月23日09:32:58
     * @author lyc


    @Override
    public MaintenancePlanDto getOne(Integer id) {
        if (id == null || Integer.valueOf(0).equals(id))
            throw new RuntimeException("ID不能为空");
        MaintenancePlanDto bean = new MaintenancePlanDto();
        EpEmMaintenancePorject project = this.getById(id);
        List<EpEmMaintenanceContent> contents = this.getContentsByProjectId(id);
        List<EpEmMaintenanceEquipment> equipments = this.getEquipmentsByProjectId(id);
        bean.setProject(project);
        bean.setContents(contents);
        bean.setEquipments(equipments);
        return bean;
    }

*
     * 查询单条数据
     *
     * @param projectId 维护计划Id
     * @param hasEm     是否需要查询设备
     * @return MaintenancePlanDto
     * @date 2020年12月23日09:32:58
     * @author lyc


    public EpEmMaintenancePlanVO getOneByVO(Integer projectId, boolean hasEm) {
        if (projectId == null || Integer.valueOf(0).equals(projectId))
            throw new RuntimeException("ID不能为空");
        EpEmMaintenancePlanVO planVO = new EpEmMaintenancePlanVO();
        EpEmMaintenancePorject project = this.getById(projectId);

        EpEmMaintenancePorjectVO projectVo = new EpEmMaintenancePorjectVO();
        BeanUtils.copyProperties(project, projectVo);

        List<EpEmMaintenanceContentVO> contentVOs = this.getContentVosByProjectId(projectId);

        planVO.setProject(projectVo);
        planVO.setContents(contentVOs);
        if (hasEm) {
            List<EpEmMaintenanceEquipmentVO> equipmentsVOs = getEquipmentVosByProjectId(projectId);
            planVO.setEquipments(equipmentsVOs);
        }
        return planVO;
    }

*
     * 通过projectId 查询 设备列表
     *
     * @param projectId 维护计划主键ID
     * @return List<EpEmMaintenanceEquipmentVO>
     * @date 2020年12月28日15:24:50
     * @author lyc


    @Override
    public List<EpEmMaintenanceEquipmentVO> getEquipmentVosByProjectId(Integer projectId) {
        EpEmMaintenancePorject project = this.getById(projectId);
        List<EpEmMaintenanceEquipment> equipments = getEquipmentsByProjectId(projectId);
        if (equipments == null || equipments.isEmpty())
            return new ArrayList<>();
        return queryEquipmentVOByList(equipments, project.getOrganizationId());
    }


*
     * 通过projectId 查询 内容列表
     *
     * @param contents 内容Ids
     * @return List<EpEmMaintenanceContentVO>
     * @date 2020年12月28日15:24:50
     * @author lyc


    public List<EpEmMaintenanceContentVO> getContentVosByContents(List<EpEmMaintenanceContent> contents) {
        Map<Integer, String> maintenanceWay = getMaintenanceWay();//维护方式
        Map<Integer, String> orgMap; //组织/部门Map
        try {
            R<List<EpOrganization>> rsp = organizationService.findAll(SecurityConstants.FROM_IN);
            List<EpOrganization> data = rsp.getData();
            orgMap = data.stream().collect(Collectors.toMap(EpOrganization::getOrganizationId, EpOrganization::getOrganizationName));
        } catch (Exception e) {
            orgMap = new HashMap<>();
        }
        Map<Integer, String> finalOrgMap = orgMap;
        List<EpEmMaintenanceContentVO> contentVOs = new ArrayList<>(contents.size());
        Set<String> userIds = new HashSet<>();
        Set<String> materielIds = new HashSet<>(); //物料集合
        contents.forEach(item -> {
            String userId = item.getUserId();
            if (StringUtils.isNoneBlank(userId)) //维护人员
                userIds.addAll(Arrays.asList(userId.split(MaintenancePlanConstant.STR_SPLIT)));
            if (item.getPublisherId() != null)//派工人员
                userIds.add(String.valueOf(item.getPublisherId()));
            if (StringUtils.isNoneBlank(item.getCatalogueId())) //物料id
                materielIds.addAll(Arrays.asList(item.getCatalogueId().split(MaintenancePlanConstant.STR_SPLIT)));
        });
        //查询用户信息
        Map<String, String> userMap = this.getUsersByIds(String.join(MaintenancePlanConstant.STR_SPLIT, userIds));
        //物料信息
        Map<String, String> materielMap = this.getMaterielByIds(String.join(MaintenancePlanConstant.STR_SPLIT, materielIds));
        contents.forEach(item -> {
            EpEmMaintenanceContentVO contentVO = new EpEmMaintenanceContentVO();
            BeanUtils.copyProperties(item, contentVO);
            if (maintenanceWay.containsKey(contentVO.getProjectMethod()))
                contentVO.setWay(maintenanceWay.get(contentVO.getProjectMethod()));
            if (finalOrgMap.containsKey(contentVO.getDepartmentId()))
                contentVO.setDepartmentName(finalOrgMap.get(contentVO.getDepartmentId()));

            Set<String> tmpWhUsers = new LinkedHashSet<>();
            Set<String> tmpDpUsers = new LinkedHashSet<>();
            Set<String> tmpMateriels = new HashSet<>(); //物料集合
            //维护人员
            String userId = item.getUserId();
            if (userId != null) {
                tmpWhUsers.addAll((Arrays.asList(userId.split(MaintenancePlanConstant.STR_SPLIT))));
            }
            //派工人员
            String publisherId = item.getPublisherId() == null ? "" : String.valueOf(item.getPublisherId());
            if (publisherId != null) {
                tmpDpUsers.add(publisherId);
            }
            if (StringUtils.isNoneBlank(item.getCatalogueId())) { //物料数据
                tmpMateriels.addAll(Arrays.asList(item.getCatalogueId().split(MaintenancePlanConstant.STR_SPLIT)));
            }
            contentVO.setMaintainUsers(boxUserNames(userMap, tmpWhUsers));
            contentVO.setDispatchUser(boxUserNames(userMap, tmpDpUsers));
            contentVO.setMaterielName(boxUserNames(materielMap, tmpMateriels));
            contentVOs.add(contentVO);
        });
        return contentVOs;
    }


*
     * 通过projectId 查询 内容列表
     *
     * @param projectIds 维护计划主键ID
     * @return List<EpEmMaintenanceContentVO>
     * @date 2020年12月28日15:24:50
     * @author lyc


    public List<EpEmMaintenanceContentVO> getContentVosByProjectIds(List<Integer> projectIds) {
        Map<Integer, String> maintenanceWay = getMaintenanceWay();//维护方式
        Map<Integer, String> orgMap; //组织/部门Map
        try {
            R<List<EpOrganization>> rsp = organizationService.findAll(SecurityConstants.FROM_IN);
            List<EpOrganization> data = rsp.getData();
            orgMap = data.stream().collect(Collectors.toMap(EpOrganization::getOrganizationId, EpOrganization::getOrganizationName));
        } catch (Exception e) {
            orgMap = new HashMap<>();
        }
        Map<Integer, String> finalOrgMap = orgMap;
        List<EpEmMaintenanceContent> contents = this.getContentsByProjectIds(projectIds);
        List<EpEmMaintenanceContentVO> contentVOs = new ArrayList<>(contents.size());
        Set<String> userIds = new HashSet<>();
        contents.forEach(item -> {
            String userId = item.getUserId();
            if (StringUtils.isNoneBlank(userId)) //维护人员
                userIds.addAll(Arrays.asList(userId.split(MaintenancePlanConstant.STR_SPLIT)));
            if (item.getPublisherId() != null)//派工人员
                userIds.add(String.valueOf(item.getPublisherId()));
        });
        //查询用户信息
        Map<String, String> userMap = this.getUsersByIds(String.join(MaintenancePlanConstant.STR_SPLIT, userIds));


        contents.forEach(item -> {
            EpEmMaintenanceContentVO contentVO = new EpEmMaintenanceContentVO();
            BeanUtils.copyProperties(item, contentVO);
            if (maintenanceWay.containsKey(contentVO.getProjectMethod()))
                contentVO.setWay(maintenanceWay.get(contentVO.getProjectMethod()));
            if (finalOrgMap.containsKey(contentVO.getDepartmentId()))
                contentVO.setDepartmentName(finalOrgMap.get(contentVO.getDepartmentId()));

            Set<String> tmpWhUsers = new LinkedHashSet<>();
            Set<String> tmpDpUsers = new LinkedHashSet<>();
            //维护人员
            String userId = item.getUserId();
            if (userId != null) {
                tmpWhUsers.addAll((Arrays.asList(userId.split(MaintenancePlanConstant.STR_SPLIT))));
            }
            //派工人员
            String publisherId = item.getPublisherId() == null ? "" : String.valueOf(item.getPublisherId());
            if (publisherId != null) {
                tmpDpUsers.add(publisherId);
            }
            contentVO.setMaintainUsers(boxUserNames(userMap, tmpWhUsers));
            contentVO.setDispatchUser(boxUserNames(userMap, tmpDpUsers));

            contentVOs.add(contentVO);
        });
        return contentVOs;
    }


*
     * 通过projectId 查询 内容列表
     *
     * @param projectId 维护计划主键ID
     * @return List<EpEmMaintenanceContentVO>
     * @date 2020年12月28日15:24:50
     * @author lyc


    @Override
    public List<EpEmMaintenanceContentVO> getContentVosByProjectId(Integer projectId) {
        Map<Integer, String> maintenanceWay = getMaintenanceWay();//维护方式
        Map<Integer, String> orgMap; //组织/部门Map
        try {
            R<List<EpOrganization>> rsp = organizationService.findAll(SecurityConstants.FROM_IN);
            List<EpOrganization> data = rsp.getData();
            orgMap = data.stream().collect(Collectors.toMap(EpOrganization::getOrganizationId, EpOrganization::getOrganizationName));
        } catch (Exception e) {
            orgMap = new HashMap<>();
        }
        Map<Integer, String> finalOrgMap = orgMap;
        List<EpEmMaintenanceContent> contents = this.getContentsByProjectId(projectId);
        EpEmMaintenancePorject project = this.getById(projectId);
        List<EpEmMaintenanceContentVO> contentVOs = new ArrayList<>(contents.size());
        Set<String> userIds = new HashSet<>();
        Set<Integer> deptIds = new HashSet<>();
        Set<String> materielIds = new HashSet<>(); //物料集合
        contents.forEach(item -> {
            String userId = item.getUserId();
            if (StringUtils.isNoneBlank(userId)) //维护人员
                userIds.addAll(Arrays.asList(userId.split(MaintenancePlanConstant.STR_SPLIT)));
            if (item.getPublisherId() != null)//派工人员
                userIds.add(String.valueOf(item.getPublisherId()));
            if (item.getDepartmentId() != null)//部门Id
                deptIds.add(item.getDepartmentId());
            if (StringUtils.isNoneBlank(item.getCatalogueId())) //物料id
                materielIds.addAll(Arrays.asList(item.getCatalogueId().split(MaintenancePlanConstant.STR_SPLIT)));
        });
        //物料  信息
        Map<String, String> materielMap = this.getMaterielByIds(String.join(MaintenancePlanConstant.STR_SPLIT, materielIds));
        //查询用户信息
        Map<String, String> userMap = this.getUsersByIds(String.join(MaintenancePlanConstant.STR_SPLIT, userIds));
        Map<Integer, List<EpUserInfo>> deptMap = this.getDeptByIds(deptIds);

        contents.forEach(item -> {
            EpEmMaintenanceContentVO contentVO = new EpEmMaintenanceContentVO();
            BeanUtils.copyProperties(item, contentVO);
            if (maintenanceWay.containsKey(contentVO.getProjectMethod()))
                contentVO.setWay(maintenanceWay.get(contentVO.getProjectMethod()));
            if (finalOrgMap.containsKey(contentVO.getDepartmentId()))
                contentVO.setDepartmentName(finalOrgMap.get(contentVO.getDepartmentId()));
            if (deptMap.containsKey(item.getDepartmentId())) {
                contentVO.setUsers(deptMap.get(item.getDepartmentId()));
            }
            //项目名称
            contentVO.setProjectName(project.getProjectName());
            //维护人员
            Set<String> tmpWhUsers = new LinkedHashSet<>();
            Set<String> tmpDpUsers = new LinkedHashSet<>();
            Set<String> tmpMateriels = new HashSet<>(); //物料集合
            String userId = item.getUserId();
            if (StringUtils.isNoneBlank(userId)) {
                tmpWhUsers.addAll(Arrays.asList(userId.split(MaintenancePlanConstant.STR_SPLIT)));
            }
            //派工人员
            String publisherId = item.getPublisherId() == null ? "" : String.valueOf(item.getPublisherId());
            if (publisherId != null) {
                tmpDpUsers.add(publisherId);
            }
            if (StringUtils.isNoneBlank(item.getCatalogueId())) { //物料数据
                tmpMateriels.addAll(Arrays.asList(item.getCatalogueId().split(MaintenancePlanConstant.STR_SPLIT)));
            }
            contentVO.setMaintainUsers(boxUserNames(userMap, tmpWhUsers));
            contentVO.setDispatchUser(boxUserNames(userMap, tmpDpUsers));
            contentVO.setMaterielName(boxUserNames(materielMap, tmpMateriels));
            contentVOs.add(contentVO);
        });
        return contentVOs;
    }


*
     * 通过维护计划Id查询年维护数据
     *
     * @param projectId 维护计划主键ID
     * @return Object
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public Object getYearHistory(Integer projectId, Integer month) {
        EpEmMaintenancePlanVO bean = this.getOneByVO(projectId, Boolean.FALSE);
        List<EpEmMaintenanceContentVO> contents = bean.getContents();
        if (contents == null || contents.isEmpty())
            return bean;
        List<Integer> contentIds = new ArrayList<>();
        contents.forEach(item -> contentIds.add(item.getContentId()));
        List<EpEmMaintenancePlan> plans = getPlansByContentIds(contentIds);
        Map<Integer, List<EpEmMaintenancePlan>> planMap = new HashMap<>();
        plans.forEach(item -> {
            Integer contentId = item.getContentId();
            if (planMap.containsKey(contentId)) {
                planMap.get(contentId).add(item);
            } else {
                planMap.put(contentId, new ArrayList<>(Collections.singletonList(item)));
            }
        });
        Map<Integer, String> maintenanceWay = getMaintenanceWay();
        contents.forEach(item -> {
            Map<Integer, Integer> monthMap = new HashMap<>();
            Map<Integer, Double> costMap = new HashMap<>();
            Integer contentId = item.getContentId();
            double costEstimate = item.getCostEstimate() == null ? 0d : item.getCostEstimate(); //单次维护成本
            if (planMap.containsKey(contentId)) {
                List<EpEmMaintenancePlan> cPlans = planMap.get(contentId);
                AtomicReference<Integer> size = new AtomicReference<>(0); //总数
                cPlans.forEach(san -> {
                    int planMonth = DateUtil.getMonthByDate(san.getPlanStartTime()); //月份
                    if (month != null && !month.equals(planMonth))
                        return;
                    monthMap.put(planMonth, monthMap.containsKey(planMonth) ? monthMap.get(planMonth) + 1 : 1);
                    costMap.put(planMonth, costMap.containsKey(planMonth) ?
                            BigDecimal.valueOf(costMap.get(planMonth)).add(BigDecimal.valueOf(costEstimate)).doubleValue() : costEstimate);
                    size.set(size.get() + 1);
                });
                item.setTimesCount(size.get());
                item.setCostCount(BigDecimal.valueOf(costEstimate)
                        .multiply(BigDecimal.valueOf(size.get()))
                        .doubleValue());
            }
            for (int i = 1; i <= MaintenancePlanConstant.MONTH; i++) {
                if (!costMap.containsKey(i))
                    costMap.put(i, 0d);
                if (!monthMap.containsKey(i))
                    monthMap.put(i, 0);
            }
            if (maintenanceWay.containsKey(item.getProjectMethod())) {//维护方式
                item.setWay(maintenanceWay.get(item.getProjectMethod()));
            }
            item.setMonthCostMap(costMap);
            item.setMonthTimesMap(monthMap);
        });
        return bean;
    }


*
     * 导出维护数据
     *
     * @param response 响应
     * @param query    查询条件
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public void exportYearHistory(HttpServletResponse response, EpEmMaintenancePorjectExportVO query) throws IOException {

        List<EpEmMaintenanceContent> contentTmps = selectByQuery(query);
        Integer orgId = query.getOrgId();
        //查询year年的所有项目
        Map<Integer, String> orgMap = new HashMap<>(); //组织/部门Map
        Map<Integer, String> teamMap = new HashMap<>(); //班组
        try {
            R<List<EpOrganization>> rsp = organizationService.findAll(SecurityConstants.FROM_IN);
            List<EpOrganization> data = rsp.getData();
            orgMap.putAll(data.stream().collect(Collectors.toMap(EpOrganization::getOrganizationId, EpOrganization::getOrganizationName)));
            R<List<WpOaTeam>> teamData = remoteGradeService.findAllCompanyWeb1(orgId, "1");
            List<WpOaTeam> data1 = teamData.getData();
            teamMap.putAll(data1.stream().collect(Collectors.toMap(WpOaTeam::getTeamId, WpOaTeam::getTeamName)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        String orgName = orgMap.getOrDefault(query.getOrgId(), ""); //组织名称
        Integer month = query.getMonth();
        Integer year = query.getYear();
        // 项目Id
        List<Integer> Ids = new ArrayList<>();
        contentTmps.forEach(project -> Ids.add(project.getProjectId()));
        Map<Integer, EpEmMaintenancePorject> pMap = new HashMap<>(); //项目Map
        if (!Ids.isEmpty()) {
            List<EpEmMaintenancePorject> projects = (List<EpEmMaintenancePorject>) this.listByIds(Ids);
            if (projects != null && !projects.isEmpty()) {
                pMap.putAll(projects.stream().collect(Collectors.toMap(EpEmMaintenancePorject::getProjectId
                        , e -> e)));
            }
        }
        Set<String> materielIds = new HashSet<>(); //物料集合
        List<EpEmMaintenanceContentVO> contents = contentTmps.stream().map(item -> {
            EpEmMaintenanceContentVO vo = new EpEmMaintenanceContentVO();
            BeanUtils.copyProperties(item, vo);
            if (StringUtils.isNoneBlank(item.getCatalogueId())) //物料id
                materielIds.addAll(Arrays.asList(item.getCatalogueId().split(MaintenancePlanConstant.STR_SPLIT)));
            return vo;
        }).collect(Collectors.toList());
        //物料  信息
        Map<String, String> materielMap = this.getMaterielByIds(String.join(MaintenancePlanConstant.STR_SPLIT, materielIds));

        Map<Integer, List<EpEmMaintenanceContentVO>> deptContentMap = new LinkedHashMap<>();
        Map<String, List<EpEmMaintenanceContentVO>> deptTeamMap = new LinkedHashMap<>();
        List<Integer> contentIds = new ArrayList<>();
        contents.forEach(item -> {
            Integer departmentId = item.getDepartmentId(); //部门Id
            String maintenanceTeam = item.getMaintenanceTeam();//维护班组
            if (deptContentMap.containsKey(departmentId)) {
                deptContentMap.get(departmentId).add(item);
            } else {
                deptContentMap.put(departmentId, new ArrayList<>(Collections.singletonList(item)));
            }
            if (StringUtils.isNoneBlank(maintenanceTeam)) { //班组处理
                String[] teams = maintenanceTeam.split(MaintenancePlanConstant.STR_SPLIT);
                for (String teamId : teams) {
                    String teamKey = departmentId + "#" + teamId;
                    if (deptTeamMap.containsKey(teamKey)) {
                        deptTeamMap.get(teamKey).add(item);
                    } else {
                        deptTeamMap.put(teamKey, new ArrayList<>(Collections.singletonList(item)));
                    }
                }
            }
            Set<String> tmpMateriels = new LinkedHashSet<>(); //处理物料数据
            if (StringUtils.isNoneBlank(item.getCatalogueId())) { //物料数据
                tmpMateriels.addAll(Arrays.asList(item.getCatalogueId().split(MaintenancePlanConstant.STR_SPLIT)));
            }
            item.setMaterielName(boxUserNames(materielMap, tmpMateriels));
            contentIds.add(item.getContentId());
        });
        List<EpEmMaintenancePlan> plans = new ArrayList<>();
        if (!contentIds.isEmpty())
            plans = getPlansByContentIds(contentIds);
        Map<Integer, List<EpEmMaintenancePlan>> planMap = new HashMap<>();
        plans.forEach(item -> {
            Integer contentId = item.getContentId();
            if (planMap.containsKey(contentId)) {
                planMap.get(contentId).add(item);
            } else {
                planMap.put(contentId, new ArrayList<>(Collections.singletonList(item)));
            }
        });
        contents.forEach(item -> {
            Map<Integer, Integer> monthMap = new HashMap<>();
            Map<Integer, Double> costMap = new HashMap<>();
            Integer contentId = item.getContentId();
            double costEstimate = item.getCostEstimate() == null ? 0d : item.getCostEstimate(); //单次维护成本
            if (planMap.containsKey(contentId)) {
                List<EpEmMaintenancePlan> cPlans = planMap.get(contentId);
                AtomicReference<Integer> size = new AtomicReference<>(0); //总数
                cPlans.forEach(san -> {
                    int planMonth = DateUtil.getMonthByDate(san.getPlanStartTime()); //月份
                    if (month != null && month != planMonth) //选择了月份
                        return;
                    monthMap.put(planMonth, monthMap.containsKey(planMonth) ? monthMap.get(planMonth) + 1 : 1);
                    costMap.put(planMonth, costMap.containsKey(planMonth) ?
                            BigDecimal.valueOf(costMap.get(planMonth)).add(BigDecimal.valueOf(costEstimate)).doubleValue() : costEstimate);
                    size.set(size.get() + 1);
                });
            }
            if (month == null) { //没选择月份 补全全部
                for (int i = 1; i <= MaintenancePlanConstant.MONTH; i++) {
                    if (!costMap.containsKey(i))
                        costMap.put(i, 0d);
                    if (!monthMap.containsKey(i))
                        monthMap.put(i, 0);
                }
            }
            item.setMonthCostMap(costMap);
            item.setMonthTimesMap(monthMap);
        });
        Map<String, Map<Integer, List<EpEmMaintenanceContentVO>>> deptPlanMap = new TreeMap<>();
        deptContentMap.forEach((key, value) -> {
            Map<Integer, List<EpEmMaintenanceContentVO>> projectMap = new LinkedHashMap<>();
            value.forEach(san -> {
                Integer projectId = san.getProjectId(); //项目Id
                if (projectMap.containsKey(projectId)) {
                    projectMap.get(projectId).add(san);
                } else {
                    projectMap.put(projectId, new ArrayList<>(Collections.singletonList(san)));
                }
            });
            deptPlanMap.put(String.valueOf(key), projectMap);
        });
        deptTeamMap.forEach((key, value) -> {
            Map<Integer, List<EpEmMaintenanceContentVO>> projectMap = new LinkedHashMap<>();
            value.forEach(san -> {
                Integer projectId = san.getProjectId(); //项目Id
                if (projectMap.containsKey(projectId)) {
                    projectMap.get(projectId).add(san);
                } else {
                    projectMap.put(projectId, new ArrayList<>(Collections.singletonList(san)));
                }
            });
            deptPlanMap.put(key, projectMap);
        });

        HSSFWorkbook workbook = new HSSFWorkbook();
        //标题样式
        CellStyle titleStyle = PointPoiUtil.createTitleStyle(workbook);
        //副标题样式
        CellStyle subTitleStyle = PointPoiUtil.createSubTitleStyle(workbook);
        //表头样式
        CellStyle headerStyle = PointPoiUtil.createHeaderStyle(workbook);
        //正文样式
        CellStyle contentStyle = PointPoiUtil.createContentStyle(workbook);
        //执行导出操作
        List<String> headerArr = new ArrayList<>();
        List<Integer> columnWidthArr = new ArrayList<>();
        List<String> mappingArr = new ArrayList<>();
        mappingArr.add("index");
        mappingArr.add("projectName");
        mappingArr.add("content");
        mappingArr.add("maintenanceStand");
        mappingArr.add("materielName");

        headerArr.add("序号");
        headerArr.add("项目名称");
        headerArr.add("维护内容");
        headerArr.add("维护标准");
        headerArr.add("物料消耗");

        columnWidthArr.add(4000);
        columnWidthArr.add(8000);
        columnWidthArr.add(12000);
        columnWidthArr.add(8000);
        columnWidthArr.add(8000);

        if (month == null) {
            for (int i = 1; i <= MaintenancePlanConstant.MONTH; i++) {
                mappingArr.add("m" + i);
                headerArr.add(i + "月");
                columnWidthArr.add(4000);
            }
        } else {
            mappingArr.add("m" + month);
            headerArr.add(month + "月");
            columnWidthArr.add(4000);
        }
        mappingArr.add("rowSum");
        headerArr.add("合计");
        columnWidthArr.add(4000);

        String maintenanceTeam = query.getMaintenanceTeam();
        deptPlanMap.forEach((key, cMap) -> {
            if (StringUtils.isNoneBlank(maintenanceTeam)) {
                List<String> teams = Arrays.asList(maintenanceTeam.split(MaintenancePlanConstant.STR_SPLIT));
                if (!key.contains("#"))
                    return;
                String[] split = key.split("#");
                String teamId = split[1];
                if (!teams.contains(teamId))
                    return;
            }
            String sheetName = "";
            if (key.contains("#")) {//含有 部门 + # +班组
                String[] split = key.split("#");
                String deptName = orgMap.getOrDefault(Integer.valueOf(split[0]), split[0]);
                String teamName = teamMap.getOrDefault(Integer.valueOf(split[1]), split[1]);
                sheetName = String.format("%s(%s)", deptName, teamName);
            } else {
                sheetName = orgMap.getOrDefault(Integer.valueOf(key), key);
            }
            List<Map<String, Object>> listMaps = new ArrayList<>();
            AtomicInteger i = new AtomicInteger(1);
            Map<Integer, Integer> colTimesMap = new HashMap<>();
            cMap.forEach((projectId, items) -> { //项目对应的内容
                items.forEach(item -> {
                    Map<Integer, Integer> monthTimesMap = item.getMonthTimesMap();
                    AtomicBoolean isNull = new AtomicBoolean(Boolean.TRUE); //判断是否全部为空
                    AtomicInteger rowSum = new AtomicInteger(0); //行合计
                    monthTimesMap.forEach((k, v) -> {
                        isNull.set(isNull.get() && (v == null || Integer.valueOf(0).equals(v)));
                        rowSum.getAndAdd(v == null ? 0 : v);
                        colTimesMap.put(k, v == null ? 0 : v + colTimesMap.getOrDefault(k, 0));
                    });
                    if (isNull.get())
                        return;
                    Map<String, Object> iMap = new HashMap<>();
                    iMap.put("index", i.get());
                    iMap.put("projectId", projectId);
                    iMap.put("projectName", pMap.get(projectId).getProjectName());
                    iMap.put("content", item.getMaintenanceMethod());
                    iMap.put("maintenanceStand", item.getMaintenanceStand());
                    iMap.put("materielName", item.getMaterielName());

                    monthTimesMap.forEach((k, v) -> iMap.put("m" + k, v));
                    iMap.put("rowSum", rowSum.get()); //行合计
                    listMaps.add(iMap);
                    i.getAndIncrement();
                });
            });
            //最下方合计
            Map<String, Object> iMap = new HashMap<>();
            iMap.put("materielName", "合计");
            AtomicInteger rowSum = new AtomicInteger(0); //行合计
            colTimesMap.forEach((k, v) -> {
                rowSum.getAndAdd(v == null ? 0 : v);
                iMap.put("m" + k, v);
            });
            iMap.put("rowSum", rowSum.get());
            listMaps.add(iMap);

            String monthStr = month != null ? month + "月" : "";
            String title = year + "年" + monthStr + orgName + MaintenancePlanConstant.MA_PLAN;
            PointPoiUtil.exportYearHistory(listMaps, workbook, titleStyle, subTitleStyle,
                    headerStyle, contentStyle, sheetName,
                    title, headerArr, columnWidthArr, mappingArr);
        });
        int sheets = workbook.getNumberOfSheets(); //sheet数
        if (sheets == 0) {
            List<Map<String, Object>> emptyMaps = new ArrayList<>();
            String title = year + "年" + orgName + MaintenancePlanConstant.MA_PLAN;
            PointPoiUtil.exportYearHistory(emptyMaps, workbook, titleStyle, subTitleStyle,
                    headerStyle, contentStyle, MaintenancePlanConstant.MA_PLAN,
                    title, headerArr, columnWidthArr, mappingArr);
        }
        exportResponse(response, workbook);
    }

*
     * 导出流
     *
     * @param response
     * @param workbook
     * @date 2020-12-24 11:38:09
     * @author lyc


    private void exportResponse(HttpServletResponse response, HSSFWorkbook workbook) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        //设置返回的文件类型
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode(MaintenancePlanConstant.MA_PLAN, "UTF8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //设置文件大小
        response.setContentLength(byteArrayOutputStream.size());
        //将流写进response输出流中
        ServletOutputStream outputstream = response.getOutputStream();
        byteArrayOutputStream.writeTo(outputstream);

        byteArrayOutputStream.close();
        outputstream.flush();
    }

*
     * 年计划复制
     *
     * @param cxyear     年份
     * @param projectIds 勾选的数据
     * @date 2020-12-24 11:38:09
     * @author lyc


    @Override
    public boolean yearPlanCopy(Integer cxyear, Integer orgId, String projectIds) {
        Integer year = cxyear == null ? LocalDate.now().getYear() : cxyear;
        //查询year 的项目
        LambdaQueryWrapper<EpEmMaintenancePorject> projectWrapper = new LambdaQueryWrapper<>();
        if (projectIds != null && !"".equals(projectIds)) {
            String[] split = projectIds.split(MaintenancePlanConstant.STR_SPLIT);
            projectWrapper.in(EpEmMaintenancePorject::getProjectId, Arrays.asList(split));
        } else {
            projectWrapper.eq(EpEmMaintenancePorject::getPlanYear, String.valueOf(year));
            projectWrapper.eq(EpEmMaintenancePorject::getOrganizationId, orgId);
        }
        List<EpEmMaintenancePorject> projects = this.list(projectWrapper);
        if (projects.isEmpty())
            return true;
        List<Integer> Ids = projects.stream().map(EpEmMaintenancePorject::getProjectId).collect(Collectors.toList());
        List<EpEmMaintenanceContent> contents = new ArrayList<>();
        List<EpEmMaintenanceEquipment> equipments = new ArrayList<>();
        try {
            equipments = getEquipmentsByProjectIds(Ids);
            contents = getContentsByProjectIds(Ids);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        Map<Integer, List<EpEmMaintenanceContent>> contentMap = new HashMap<>();
        List<Integer> contentIds = new ArrayList<>();
        contents.forEach(item -> {
            Integer projectId = item.getProjectId();
            if (contentMap.containsKey(projectId)) {
                contentMap.get(projectId).add(item);
            } else {
                contentMap.put(projectId, new ArrayList<>(Collections.singletonList(item)));
            }
            contentIds.add(item.getContentId());
        });

        Map<Integer, List<EpEmMaintenanceEquipment>> equipmentMap = new HashMap<>();
        equipments.forEach(item -> {
            Integer projectId = item.getProjectId();
            if (equipmentMap.containsKey(projectId)) {
                equipmentMap.get(projectId).add(item);
            } else {
                equipmentMap.put(projectId, new ArrayList<>(Collections.singletonList(item)));
            }
        });
        //计划数据
        List<EpEmMaintenancePlan> plans = new ArrayList<>();
        try {
            plans = getPlansByContentIds(contentIds);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        Map<Integer, List<EpEmMaintenancePlan>> planMap = new HashMap<>();
        List<Integer> planIds = new ArrayList<>();
        plans.forEach(item -> {
            Integer contentId = item.getContentId();
            if (planMap.containsKey(contentId)) {
                planMap.get(contentId).add(item);
            } else {
                planMap.put(contentId, new ArrayList<>(Collections.singletonList(item)));
            }
            planIds.add(item.getPlanId());
        });
        Map<Integer, List<EpEmMaintenanceRecord>> recordMap = new HashMap<>();
        List<EpEmMaintenanceRecord> records = new ArrayList<>();
        try {
            records = getRecordByPlanIds(planIds);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        records.forEach(item -> {
            Integer contentId = item.getPlanId();
            if (recordMap.containsKey(contentId)) {
                recordMap.get(contentId).add(item);
            } else {
                recordMap.put(contentId, new ArrayList<>(Collections.singletonList(item)));
            }
        });
        projects.forEach(item -> {
            Integer oldProjectId = item.getProjectId(); //之前的projectId
            //添加项目
            item.setPlanYear(String.valueOf(Integer.parseInt(item.getPlanYear()) + 1)); //下一年
            this.save(item);
            Integer projectId = item.getProjectId(); //新增的projectId
            if (contentMap.containsKey(oldProjectId)) {
                List<EpEmMaintenanceContent> contentList = contentMap.get(oldProjectId);
                contentList.forEach(content -> {
                    Integer oldContentId = content.getContentId(); //之前的contentId
                    content.setProjectId(projectId);
                    epEmMaintenanceContentDao.insert(content);
                    Integer contentId = content.getContentId();
                    if (planMap.containsKey(oldContentId)) {
                        List<EpEmMaintenancePlan> oldPlans = planMap.get(oldContentId);
                        oldPlans.forEach(plan -> {
                            Integer oldPlanId = plan.getPlanId();//之前的planId
                            plan.setPlanStartTime(DateUtil.addOneYear(plan.getPlanStartTime()));
                            plan.setPlanEndTime(DateUtil.addOneYear(plan.getPlanEndTime()));
                            plan.setRemindDay(DateUtil.addOneYear(plan.getRemindDay()));
                            plan.setContentId(contentId);
                            epEmMaintenancePlanDao.insert(plan);
                            Integer planId = plan.getPlanId();//新增的planId
                            if (recordMap.containsKey(oldPlanId)) {
                                recordMap.get(oldPlanId).forEach(record -> {
                                    record.setPlanId(planId);
                                    record.setRecordTime(new Date());
                                    epEmMaintenanceRecordDao.insert(record);
                                });
                            }
                        });
                    }
                });
            }
            if (equipmentMap.containsKey(oldProjectId)) {
                List<EpEmMaintenanceEquipment> equipmentList = equipmentMap.get(oldProjectId);
                equipmentList.forEach(equipment -> {
                    equipment.setProjectId(projectId);
                    epEmMaintenanceEquipmentDao.insert(equipment);
                });
            }
        });
        return true;
    }

*
     * 项目计划复制
     *
     * @param oldProjectId 项目Id
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public boolean projectPlanCopy(Integer oldProjectId) {
        //查询year 的项目
        LambdaQueryWrapper<EpEmMaintenancePorject> projectWrapper = new LambdaQueryWrapper<>();
        projectWrapper.eq(EpEmMaintenancePorject::getProjectId, oldProjectId);
        EpEmMaintenancePorject project = this.getOne(projectWrapper);
        if (project == null)
            return false;
        project.setOrderId(project.getOrderId() + 1);
        this.save(project);
        Integer projectId = project.getProjectId(); //新增Id

        List<EpEmMaintenanceContent> contents = getContentsByProjectId(oldProjectId);
        if (contents == null || contents.isEmpty())
            return false;

        List<Integer> contentIds = new ArrayList<>();
        contents.forEach(item -> contentIds.add(item.getContentId()));
        //计划数据
        List<EpEmMaintenancePlan> plans = getPlansByContentIds(contentIds);
        Map<Integer, List<EpEmMaintenancePlan>> planMap = new HashMap<>();
        List<Integer> planIds = new ArrayList<>();
        plans.forEach(item -> {
            Integer contentId = item.getContentId();
            if (planMap.containsKey(contentId)) {
                planMap.get(contentId).add(item);
            } else {
                planMap.put(contentId, new ArrayList<>(Collections.singletonList(item)));
            }
            planIds.add(item.getPlanId());
        });
        List<EpEmMaintenanceRecord> records = getRecordByPlanIds(planIds);
        Map<Integer, List<EpEmMaintenanceRecord>> recordMap = new HashMap<>();
        records.forEach(item -> {
            Integer contentId = item.getPlanId();
            if (recordMap.containsKey(contentId)) {
                recordMap.get(contentId).add(item);
            } else {
                recordMap.put(contentId, new ArrayList<>(Collections.singletonList(item)));
            }
        });
        contents.forEach(item -> {
            Integer oldContentId = item.getContentId();//之前的contentId
            item.setProjectId(projectId);
            epEmMaintenanceContentDao.insert(item);
            Integer contentId = item.getContentId();//新增的Id
            if (planMap.containsKey(oldContentId)) {
                List<EpEmMaintenancePlan> oldPlans = planMap.get(oldContentId);
                oldPlans.forEach(plan -> {
                    Integer oldPlanId = plan.getPlanId();//之前的planId
                    plan.setContentId(contentId);
                    epEmMaintenancePlanDao.insert(plan);
                    Integer planId = plan.getPlanId();//新增的planId
                    if (recordMap.containsKey(oldPlanId)) {
                        recordMap.get(oldPlanId).forEach(record -> {
                            record.setPlanId(planId);
                            record.setRecordTime(new Date());
                            epEmMaintenanceRecordDao.insert(record);
                        });
                    }
                });
            }
        });
        return true;
    }

*
     * 添加项目数据
     *
     * @param bean 添加的数据
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public EpEmMaintenancePorject addProject(EpEmMaintenancePorject bean) {
        checkProject(bean, Boolean.FALSE);
        this.save(bean);
        return bean;
    }

*
     * 更新项目数据
     *
     * @param bean 添加的数据
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public EpEmMaintenancePorject updProject(EpEmMaintenancePorject bean) {
        checkProject(bean, Boolean.TRUE);
        this.updateById(bean);
        return bean;
    }

*
     * 添加维护内容数据
     *
     * @param bean 添加的数据
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public EpEmMaintenanceContent addContent(EpEmMaintenanceContent bean) {
        checkContent(bean, Boolean.FALSE);
        //设置人员为空
        bean.setUserId(null);
        bean.setPublisherId(null);
        epEmMaintenanceContentDao.insert(bean);

        addPlanContent(bean);
        return bean;
    }


*
     * 添加计划数据
     * 一个计划只对应一个记录
     * APP 维护人员都能看到 ，只有一个完成就是已完成
     *
     * @param bean 添加的数据
     * @date 2020年12月22日15:17:34
     * @author lyc


    public void addPlanContent(EpEmMaintenanceContent bean) {
        List<EpEmMaintenancePlan> plans = this.doHandlePlan(bean);
        plans.forEach(plan -> {
            epEmMaintenancePlanDao.insert(plan);
            Integer planId = plan.getPlanId();//计划Id
            EpEmMaintenanceRecord record = new EpEmMaintenanceRecord();
            record.setPlanId(planId);
            record.setWorkHours(bean.getHourEstimate()); //默认预估工时
            record.setStopTime(0d);//停机时长 默认0
            record.setMaintenanceUser(0); //默认0
            record.setMaintenanceContent(bean.getMaintenanceMethod());
            record.setRecordTime(new Date());
            epEmMaintenanceRecordDao.insert(record);
        });
    }

*
     * 添加维护内容数据
     *
     * @param bean 添加的数据
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public EpEmMaintenanceContent updContent(EpEmMaintenanceContent bean) {
        checkContent(bean, Boolean.TRUE);
        Integer contentId = bean.getContentId();
        EpEmMaintenanceContent content = epEmMaintenanceContentDao.selectById(contentId);
        Integer publisherId = content.getPublisherId();
        String userId = content.getUserId();
        //防止修改人员
        bean.setPublisherId(publisherId);
        bean.setUserId(userId);
        epEmMaintenanceContentDao.updateById(bean);
        //删除计划数据
        delContentPlan(Collections.singletonList(bean.getContentId()));

        //添加计划数据
        addPlanContent(bean);
        return bean;
    }

*
     * 删除维护内容数据
     *
     * @param ids Id数据
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public boolean delContent(String ids) {
        try {
            if (ids == null || "".equals(ids))
                throw new Exception("ID不能为空");
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }
        String[] split = ids.split(MaintenancePlanConstant.STR_SPLIT);
        List<Integer> contentIds = new ArrayList<>(Arrays.asList(split)).stream().map(Integer::parseInt).collect(Collectors.toList());
        if (contentIds.isEmpty())
            return true;
        return delContent(contentIds);
    }


*
     * 删除维护内容数据
     *
     * @param contentIds Id数据
     * @date 2020年12月22日15:17:34
     * @author lyc


    public boolean delContent(List<Integer> contentIds) {
        epEmMaintenanceContentDao.deleteBatchIds(contentIds);
        delContentPlan(contentIds);
        return true;
    }

*
     * 删除维护内容计划数据
     *
     * @param contentIds Id数据
     * @date 2020年12月22日15:17:34
     * @author lyc


    public void delContentPlan(List<Integer> contentIds) {
        //查询计划记录数据
        LambdaQueryWrapper<EpEmMaintenancePlan> planList = new LambdaQueryWrapper<>();
        planList.in(EpEmMaintenancePlan::getContentId, contentIds);
        List<EpEmMaintenancePlan> plans = epEmMaintenancePlanDao.selectList(planList);
        List<Integer> planIds = plans.stream().map(EpEmMaintenancePlan::getPlanId).collect(Collectors.toList());

        LambdaQueryWrapper<EpEmMaintenanceRecord> recordList = new LambdaQueryWrapper<>();
        recordList.in(EpEmMaintenanceRecord::getPlanId, planIds);
        List<EpEmMaintenanceRecord> records = epEmMaintenanceRecordDao.selectList(recordList);
        List<Integer> recordsIds = records.stream().map(EpEmMaintenanceRecord::getMaintenanceRecordId).collect(Collectors.toList());


        //删除计划数据
        LambdaUpdateWrapper<EpEmMaintenancePlan> planDel = new LambdaUpdateWrapper<>();
        planDel.in(EpEmMaintenancePlan::getContentId, contentIds);
        epEmMaintenancePlanDao.delete(planDel);
        //删除计划记录数据
        LambdaUpdateWrapper<EpEmMaintenanceRecord> recordDel = new LambdaUpdateWrapper<>();
        recordDel.in(EpEmMaintenanceRecord::getPlanId, planIds);
        epEmMaintenanceRecordDao.delete(recordDel);
        //删除计划记录-文件数据
        LambdaUpdateWrapper<WpOmMaintenanceFile> fileDel = new LambdaUpdateWrapper<>();
        fileDel.in(WpOmMaintenanceFile::getMaintenanceRecordId, recordsIds);
        epEmMaintenanceRecordFileDao.delete(fileDel);
    }

*
     * 添加维护设备数据
     *
     * @param map 参数集
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public List<EpEmMaintenanceEquipmentVO> addEquipment(Map<String, Object> map) {
        Integer projectId = Integer.valueOf(String.valueOf(map.get("projectId")));
        String equipmentIds = String.valueOf(map.get("equipmentIds"));
        try {
            if (projectId == null)
                throw new Exception("维护项目Id不能为空");
            if (equipmentIds == null || "".equals(equipmentIds))
                throw new Exception("设备Id不能为空");
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }
        EpEmMaintenancePorject project = this.getById(projectId);
        //查询所有的设备数据
        List<EpEmMaintenanceEquipment> dbEquipments = getEquipmentsByProjectId(projectId);
        List<Integer> dbIds = dbEquipments.stream().map(EpEmMaintenanceEquipment::getEquipmentId).collect(Collectors.toList());
        //维护设备新增
        String[] split = equipmentIds.split(MaintenancePlanConstant.STR_SPLIT);
        for (String Id : split) {
            Integer equipmentId = Integer.valueOf(Id);
            if (dbIds.contains(equipmentId)) { //数据库存在则不添加
                continue;
            }
            EpEmMaintenanceEquipment bean = new EpEmMaintenanceEquipment();
            bean.setEquipmentId(Integer.valueOf(Id));
            bean.setProjectId(projectId);
            epEmMaintenanceEquipmentDao.insert(bean);
        }
        //查询所有的设备数据
        List<EpEmMaintenanceEquipment> equipments = getEquipmentsByProjectId(projectId);
        return queryEquipmentVOByList(equipments, project.getOrganizationId());
    }

*
     * 通过设备集合查询设备信息
     *
     * @param equipments 设备数据
     * @date 2020-12-25 09:50:30
     * @author lyc


    private List<EpEmMaintenanceEquipmentVO> queryEquipmentVOByList(List<EpEmMaintenanceEquipment> equipments, Integer organizationId) {
        List<EpEmMaintenanceEquipmentVO> equipmentsVOs = new ArrayList<>(equipments.size());

        equipments.forEach(item -> {
            EpEmMaintenanceEquipmentVO equipmentVO = new EpEmMaintenanceEquipmentVO();
            BeanUtils.copyProperties(item, equipmentVO);
            try {
                EpEmEquipmentVO ep = epEmEquipmentService.findEpEmEquipmentVOById(equipmentVO.getEquipmentId(), organizationId);
                equipmentVO.setEquipmentName(ep.getEquipmentName());
                equipmentVO.setFacName(ep.getUnitName());
                equipmentVO.setEquipmentNum(ep.getEquipmentNum());
                equipmentVO.setMaintainerServiceName(ep.getProduceServiceName());
                List<String> strings = Arrays.asList(ep.getTypeName(), ep.getEquipmentTypeIdName());
                String collect = strings.stream().filter(StringUtils::isNotBlank).collect(Collectors.joining("-"));
                equipmentVO.setTypeName(collect);
                equipmentVO.setLevel(ep.getEquipmentLevel());
                equipmentVO.setMateriel(emptyString(ep.getMaterielName()) + emptyString(ep.getModelName()));
                equipmentVO.setStartDate(ep.getStartDate());
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            equipmentsVOs.add(equipmentVO);
        });

        return equipmentsVOs;
    }

*
     * 空字符处理
     *
     * @param obj 字符串
     * @date 2020年12月22日15:17:34
     * @author lyc


    private String emptyString(String obj) {
        return obj == null ? "" : obj;
    }


*
     * 删除维护设备数据
     *
     * @param ids 数据
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public boolean delEquipment(String ids) {
        try {
            if (ids == null || "".equals(ids))
                throw new Exception("ID不能为空");
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }
        String[] split = ids.split(MaintenancePlanConstant.STR_SPLIT);
        epEmMaintenanceEquipmentDao.deleteBatchIds(Arrays.asList(split));
        return true;
    }

*
     * 派工操作
     *
     * @param contents 数据
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public boolean addDispatch(List<EpEmMaintenanceContent> contents) {
        List<Integer> contentIds = new ArrayList<>();
        try {
            if (contents == null || contents.isEmpty())
                throw new Exception("数据不能为空");
            for (EpEmMaintenanceContent item : contents) {
                Integer contentId = item.getContentId();
                if (contentId == null || contentId == 0) {
                    throw new Exception("contentId不能为空");
                }
                if (item.getUserId() == null || "".equals(item.getUserId())) {
                    throw new Exception("维护人员不能为空");
                }
                if (item.getPublisherId() == null || item.getPublisherId() == 0) {
                    throw new Exception("派工人员不能为空");
                }
                contentIds.add(item.getContentId());
            }
            List<EpEmMaintenanceContent> dbContents = epEmMaintenanceContentDao.selectBatchIds(contentIds);
            List<Integer> dbContentIds = dbContents.stream().map(EpEmMaintenanceContent::getContentId).collect(Collectors.toList());

            for (EpEmMaintenanceContent item : contents) {
                if (!dbContentIds.contains(item.getContentId())) {
                    throw new Exception("数据不存在");
                }
            }
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }
        //更新维护人员和派工人员
        contents.forEach(item -> {
            LambdaUpdateWrapper<EpEmMaintenanceContent> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(EpEmMaintenanceContent::getUserId, item.getUserId())
                    .set(EpEmMaintenanceContent::getPublisherId, item.getPublisherId())
                    .eq(EpEmMaintenanceContent::getContentId, item.getContentId());
            epEmMaintenanceContentDao.update(item, updateWrapper);
        });
        return true;
    }

*
     * 查询维护年历的数据分页
     *
     * @param query 分页器
     * @return Object
     * @date 2020年12月29日16:59:25
     * @author lyc


    @Override
    public IPage queryYearData(EpEmMaintenancePorjectFormVO query) {
        if (query == null)
            query = new EpEmMaintenancePorjectFormVO();
        Page page = new Page();
        BeanUtils.copyProperties(query, page);
        if (query.getYear() == null) {
            query.setYear(LocalDate.now().getYear());
        }
        IPage iPage = epEmMaintenancePlanDao.queryYearPage(page, query.getYear(), query.getOrgId());
        List<EpEmMaintenanceContent> records = iPage.getRecords();
        if (records == null || records.isEmpty())
            return iPage;
        //项目Id集合
        List<Integer> projectIds = records.stream().map(EpEmMaintenanceContent::getProjectId).distinct().collect(Collectors.toList());
        LambdaQueryWrapper<EpEmMaintenancePorject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EpEmMaintenancePorject::getProjectId, projectIds);
        List<EpEmMaintenancePorject> projects = this.list(queryWrapper);

        //项目Map
        Map<Integer, String> projectMap = projects.stream().collect(Collectors.toMap(EpEmMaintenancePorject::getProjectId, EpEmMaintenancePorject::getProjectName));

        //内容数据集合
        List<EpEmMaintenanceContentVO> contents = this.getContentVosByContents(records);

        List<Integer> contentIds = contents.stream().map(EpEmMaintenanceContentVO::getContentId).collect(Collectors.toList());
        List<EpEmMaintenancePlan> plans = getPlansByContentIds(contentIds);
        Map<Integer, List<EpEmMaintenancePlan>> planMap = new HashMap<>();
        List<Integer> planIds = new ArrayList<>();
        plans.forEach(item -> {
            Integer contentId = item.getContentId();
            if (planMap.containsKey(contentId)) {
                planMap.get(contentId).add(item);
            } else {
                planMap.put(contentId, new ArrayList<>(Collections.singletonList(item)));
            }
            planIds.add(item.getPlanId());
        });
        //记录数据 以planId 为key
        Map<Integer, EpEmMaintenanceRecordAppVO> recordMap = getRecordVoMapByPlanIds(planIds);
        List<EpEmMaintenancePlanYearVO> items = new ArrayList<>();
        contents.forEach(content -> {
            EpEmMaintenancePlanYearVO item = new EpEmMaintenancePlanYearVO();
            BeanUtils.copyProperties(content, item);
            Map<Integer, Map<String, Integer>> monthTimesMap = new HashMap<>();
            Map<Integer, Map<String, BigDecimal>> monthCostMap = new HashMap<>();
            Integer contentId = item.getContentId();
            item.setProjectName(projectMap.getOrDefault(item.getProjectId(), ""));
            if (planMap.containsKey(contentId)) {
                List<EpEmMaintenancePlan> cPlans = planMap.get(contentId);
                cPlans.forEach(plan -> handleCountMap(item, plan, recordMap, monthTimesMap, monthCostMap));
            }
            sumMap(item, monthTimesMap, monthCostMap);
            item.setMonthTimesMap(monthTimesMap);
            item.setMonthCostMap(monthCostMap);
            items.add(item);
        });

        iPage.setRecords(items);
        return iPage;
    }

*
     * 点击查看维护记录
     *
     * @param query 分页器
     * @return Object
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public Object getPlansByData(MaintenancePlanYearDto query) {
        EpEmMaintenanceContent content;
        Integer contentId;
        try {
            if (query == null)
                throw new Exception("数据不能为空");
            if (query.getMonth() == null)
                throw new Exception("月份数据不能为空");
            if (query.getContentId() == null)
                throw new Exception("内容ID不能为空");
            contentId = query.getContentId();// 内容Id
            content = epEmMaintenanceContentDao.selectById(contentId);
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }
        String userId = content.getUserId(); //用户Id
        String userName = "";
        if (StringUtils.isNotBlank(userId)) {//查询用户信息
            List<EpUserInfo> users = remoteLoginService.selectByUserIds(userId, SecurityConstants.FROM_IN);
            userName = users != null && !users.isEmpty() ?
                    users.stream().map(EpUserInfo::getUserName).collect(Collectors.joining(MaintenancePlanConstant.STR_SPLIT))
                    : "";
        }
        Integer month = query.getMonth(); //月份
        List<EpEmMaintenancePlan> plans = getMonthPlansByContentId(month, contentId);
        if (plans == null || plans.isEmpty())
            return plans;

        List<Integer> planIds = plans.stream().map(EpEmMaintenancePlan::getPlanId).collect(Collectors.toList());
        Map<Integer, EpEmMaintenanceRecordAppVO> recordMap = getRecordVoMapByPlanIds(planIds);

        List<EpEmMaintenancePlanInfoVO> newPlans = new ArrayList<>();
        String finalUserName = userName;
        plans.forEach(item -> {
            EpEmMaintenancePlanInfoVO vo = new EpEmMaintenancePlanInfoVO();
            BeanUtils.copyProperties(item, vo);
            Integer planId = vo.getPlanId();
            Date planEndTime = item.getPlanEndTime();
            if (recordMap.containsKey(planId)) {
                EpEmMaintenanceRecordAppVO record = recordMap.get(planId);
                vo.setWorkHours(BigDecimal.valueOf(record.getWorkHours()));
                vo.setStopTime(BigDecimal.valueOf(record.getStopTime()));
                vo.setMaintenanceContent(record.getMaintenanceContent());
                Date completeTime = record.getCompleteTime();
                vo.setCompleteTime(completeTime);
                //判断是否超期
                if (planEndTime != null && completeTime != null && completeTime.getTime() > planEndTime.getTime())
                    vo.setIsOver(1);
                vo.setActCost(record.getLossCost());//实际支出
                vo.setLossDetail(record.getLossDetail());//支出明细
            }
            vo.setCostEstimate(BigDecimal.valueOf(content.getCostEstimate() == null ? 0d : content.getCostEstimate()));//成本估算
            vo.setMaintenanceMethod(content.getMaintenanceMethod()); //维护要求
            vo.setMaintenanceUser(finalUserName);
            newPlans.add(vo);
        });
        return newPlans;
    }

*
     * 获取维护记录
     *
     * @param contentId id
     * @return Object
     * @date 2020年12月22日15:17:34
     * @author lyc


    @Override
    public Object getContentById(Integer contentId) {
        try {
            if (contentId == null)
                throw new Exception("contentId不能为空");
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }
        EpEmMaintenanceContent content = epEmMaintenanceContentDao.selectById(contentId);
        return content;
    }


*
     * 统计Map数据
     *
     * @param item          内容数据
     * @param monthTimesMap 月次数map
     * @param monthCostMap  月成本map
     * @date 2020年12月30日11:16:27
     * @author lyc


    private void sumMap(EpEmMaintenancePlanYearVO item,
                        Map<Integer, Map<String, Integer>> monthTimesMap,
                        Map<Integer, Map<String, BigDecimal>> monthCostMap) {

        //计划维护次数总和
        Integer planTimesCount = 0;

        //实际维护次数总和
        Integer actTimesCount = 0;

        //实际超期维护次数总和
        Integer actOverTimesCount = 0;

        //完成率(%)
        BigDecimal finishRate;

        //超期率(%)
        BigDecimal overRate;

        //计划维护成本总计
        BigDecimal planCostCount = BigDecimal.ZERO;

        // 实际维护成本总和
        BigDecimal actCostCount = BigDecimal.ZERO;

        //超支金额
        BigDecimal overCost;

        for (int i = 1; i <= MaintenancePlanConstant.MONTH; i++) {
            Map<String, Integer> times = new HashMap<>();
            if (!monthTimesMap.containsKey(i)) {
                times.put(MaintenancePlanConstant.KEY_PLAN, 0);
                times.put(MaintenancePlanConstant.KEY_ACT, 0);
                times.put(MaintenancePlanConstant.KEY_ACT_OVER, 0);
                monthTimesMap.put(i, times);
            } else {
                times = monthTimesMap.get(i);
                if (!times.containsKey(MaintenancePlanConstant.KEY_PLAN))
                    times.put(MaintenancePlanConstant.KEY_PLAN, 0);
                if (!times.containsKey(MaintenancePlanConstant.KEY_ACT))
                    times.put(MaintenancePlanConstant.KEY_ACT, 0);
                if (!times.containsKey(MaintenancePlanConstant.KEY_ACT_OVER))
                    times.put(MaintenancePlanConstant.KEY_ACT_OVER, 0);
                Integer plan = times.getOrDefault(MaintenancePlanConstant.KEY_PLAN, 0);//计划次数
                Integer act = times.getOrDefault(MaintenancePlanConstant.KEY_ACT, 0);//实际次数
                Integer actOver = times.getOrDefault(MaintenancePlanConstant.KEY_ACT_OVER, 0);//实际超期

                planTimesCount = planTimesCount + plan;
                actTimesCount = actTimesCount + act;
                actOverTimesCount = actOverTimesCount + actOver;
            }
            Map<String, BigDecimal> costMap = new HashMap<>();
            if (!monthCostMap.containsKey(i)) {
                costMap.put(MaintenancePlanConstant.KEY_PLAN, BigDecimal.ZERO);
                costMap.put(MaintenancePlanConstant.KEY_ACT, BigDecimal.ZERO);
                monthCostMap.put(i, costMap);
            } else {
                costMap = monthCostMap.get(i);
                if (!costMap.containsKey(MaintenancePlanConstant.KEY_PLAN))
                    costMap.put(MaintenancePlanConstant.KEY_PLAN, BigDecimal.ZERO);
                if (!costMap.containsKey(MaintenancePlanConstant.KEY_ACT))
                    costMap.put(MaintenancePlanConstant.KEY_ACT, BigDecimal.ZERO);
                BigDecimal plan = costMap.getOrDefault(MaintenancePlanConstant.KEY_PLAN, BigDecimal.ZERO); //计划成本
                BigDecimal act = costMap.getOrDefault(MaintenancePlanConstant.KEY_ACT, BigDecimal.ZERO); //实际成本
                planCostCount = planCostCount.add(plan);
                actCostCount = actCostCount.add(act);
            }
        }

        finishRate = (actTimesCount == 0 || planTimesCount == 0) ?
                BigDecimal.ZERO :
                BigDecimal.valueOf(actTimesCount)
                        .divide(BigDecimal.valueOf(planTimesCount), 2, BigDecimal.ROUND_HALF_EVEN)
                        .multiply(BigDecimal.valueOf(100));

        overRate = (actOverTimesCount == 0 || actTimesCount == 0) ?
                BigDecimal.ZERO :
                BigDecimal.valueOf(actOverTimesCount)
                        .divide(BigDecimal.valueOf(actTimesCount), 2, BigDecimal.ROUND_HALF_EVEN)
                        .multiply(BigDecimal.valueOf(100));

        overCost = actCostCount.subtract(planCostCount);
        item.setPlanTimesCount(planTimesCount);
        item.setActTimesCount(actTimesCount);
        item.setActOverTimesCount(actOverTimesCount);
        item.setFinishRate(finishRate);
        item.setOverRate(overRate);
        item.setPlanCostCount(planCostCount);
        item.setActCostCount(actCostCount);
        item.setOverCost(overCost);
    }

*
     * 处理对应Map的数据
     *
     * @param content       内容数据
     * @param plan          计划数据
     * @param recordMap     记录数据
     * @param monthTimesMap 月次数map
     * @param monthCostMap  月成本map
     * @date 2020年12月30日11:16:27
     * @author lyc


    private void handleCountMap(EpEmMaintenancePlanYearVO content,
                                EpEmMaintenancePlan plan,
                                Map<Integer, EpEmMaintenanceRecordAppVO> recordMap,
                                Map<Integer, Map<String, Integer>> monthTimesMap,
                                Map<Integer, Map<String, BigDecimal>> monthCostMap) {
        EpEmMaintenanceRecordAppVO record = recordMap.getOrDefault(plan.getPlanId(), new EpEmMaintenanceRecordAppVO());//记录数据
        boolean flag = record.getCompleteTime() != null; //判断是否完成 true 完成 false未完成
        int planMonth = DateUtil.getMonthByDate(plan.getPlanStartTime()); //月份

        BigDecimal costEstimate = BigDecimal.valueOf(content.getCostEstimate() == null ? 0d : content.getCostEstimate()); //计划成本
        BigDecimal lossCost = record.getLossCost() == null ? BigDecimal.ZERO : record.getLossCost(); //实际成本
        if (monthTimesMap.containsKey(planMonth)) {
            //统计次数
            Map<String, Integer> countMap = monthTimesMap.get(planMonth);
            countMap.put(MaintenancePlanConstant.KEY_PLAN, countMap.getOrDefault(MaintenancePlanConstant.KEY_PLAN, 0) + 1); //计划数量
            //统计成本
            Map<String, BigDecimal> costMap = monthCostMap.get(planMonth);
            costMap.put(MaintenancePlanConstant.KEY_PLAN, costMap.getOrDefault(MaintenancePlanConstant.KEY_PLAN, BigDecimal.ZERO).add(costEstimate)); //计划成本
            if (flag) { //已完成 统计实际数据
                //统计次数
                countMap.put(MaintenancePlanConstant.KEY_ACT, countMap.getOrDefault(MaintenancePlanConstant.KEY_ACT, 0) + 1);//实际
                if (plan.getPlanEndTime() != null && record.getCompleteTime().getTime() > plan.getPlanEndTime().getTime()) //实际完成时间大于 计划完成时间
                    countMap.put(MaintenancePlanConstant.KEY_ACT_OVER, countMap.getOrDefault(MaintenancePlanConstant.KEY_ACT_OVER, 0) + 1);//实际超期
                //统计成本
                costMap.put(MaintenancePlanConstant.KEY_ACT, costMap.getOrDefault(MaintenancePlanConstant.KEY_ACT, BigDecimal.ZERO).add(lossCost)); //实际成本
            }
        } else {
            Map<String, Integer> countMap = new HashMap<>(); //计划次数
            Map<String, BigDecimal> costMap = new HashMap<>();//计划成本

            costMap.put(MaintenancePlanConstant.KEY_PLAN, costEstimate); //计划成本
            countMap.put(MaintenancePlanConstant.KEY_PLAN, 1); //计划数量
            if (flag) { //已完成 统计实际数据
                countMap.put(MaintenancePlanConstant.KEY_ACT, 1);//实际
                if (plan.getPlanEndTime() != null && record.getCompleteTime().getTime() > plan.getPlanEndTime().getTime()) //实际完成时间大于 计划完成时间
                    countMap.put(MaintenancePlanConstant.KEY_ACT_OVER, 1);//实际超期
                costMap.put(MaintenancePlanConstant.KEY_ACT, lossCost); //实际成本
            }
            monthTimesMap.put(planMonth, countMap);
            monthCostMap.put(planMonth, costMap);
        }
    }


*
     * 通过planId查询记录数
     *
     * @return List<EpEmMaintenanceRecord>
     * @date 2020-12-23 16:02:07
     * @author lyc


    private List<EpEmMaintenanceRecord> getRecordByPlanIds(List<Integer> planIds) {
        if (planIds == null || planIds.isEmpty())
            return null;
        LambdaQueryWrapper<EpEmMaintenanceRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EpEmMaintenanceRecord::getPlanId, planIds);
        return epEmMaintenanceRecordDao.selectList(queryWrapper);
    }

*
     * 通过planId查询记录数
     *
     * @return Map<Integer, EpEmMaintenanceRecord>
     * @date 2020-12-23 16:02:07
     * @author lyc


    public Map<Integer, EpEmMaintenanceRecordAppVO> getRecordVoMapByPlanIds(List<Integer> planIds) {
        Map<Integer, EpEmMaintenanceRecordAppVO> map = new HashMap<>();
        List<EpEmMaintenanceRecord> records = getRecordByPlanIds(planIds);
        if (records == null || records.isEmpty())
            return map;
        List<Integer> recordIds = records.stream().map(EpEmMaintenanceRecord::getMaintenanceRecordId).collect(Collectors.toList());

        LambdaQueryWrapper<EpEmMaintenanceCost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EpEmMaintenanceCost::getMaintenanceRecordId, recordIds);
        List<EpEmMaintenanceCost> costs = epEmMaintenanceCostDao.selectList(queryWrapper);
        Map<Integer, List<EpEmMaintenanceCost>> costMap = new HashMap<>();
        costs.forEach(cost -> {
            Integer recordId = cost.getMaintenanceRecordId();//记录Id
            if (costMap.containsKey(recordId)) {
                costMap.get(recordId).add(cost);
            } else {
                costMap.put(recordId, new ArrayList<>(Collections.singletonList(cost)));
            }
        });
        //将耗材的数量和金额赋值
        return records.stream().map(item -> {
            EpEmMaintenanceRecordAppVO vo = new EpEmMaintenanceRecordAppVO();
            BeanUtils.copyProperties(item, vo);
            Integer recordId = vo.getMaintenanceRecordId();
            if (costMap.containsKey(recordId)) {
                List<EpEmMaintenanceCost> sans = costMap.get(recordId);
                AtomicReference<BigDecimal> sum = new AtomicReference<>(BigDecimal.ZERO);
                List<String> details = new ArrayList<>();
                sans.forEach(cost -> {
                    Double unitCost = cost.getUnitCost();//每项的单位小计
                    String detail = String.format("%s(%s-%s-%s)%d%s%.2f(元)",
                            emptyString(cost.getMaterielName()),
                            emptyString(cost.getMadeCountry()),
                            emptyString(cost.getMaterielBrand()),
                            emptyString(cost.getMaterielModel()),
                            cost.getUseNum(),
                            emptyString(cost.getUnitName()),
                            cost.getUnitCost());
                    details.add(detail);
                    sum.set(sum.get().add(BigDecimal.valueOf(unitCost)));
                });
                vo.setLossDetail(String.join(MaintenancePlanConstant.STR_SPLIT, details));
                vo.setLossCost(sum.get());
                vo.setLossCount(sans.size());
            }
            return vo;
        }).collect(Collectors.toMap(EpEmMaintenanceRecordAppVO::getPlanId, e -> e));
    }

*
     * 获取保养部位
     *
     * @return Map<Integer, String>
     * @date 2020-12-23 16:02:07
     * @author lyc


    public Map<Integer, String> getMaintenancePart() {
        List<DwIdCdMaintenance> items = epEmMaintenanceService.findDwIdCdMaintenance(0);
        Map<Integer, String> map = items.stream().collect(Collectors.toMap(DwIdCdMaintenance::getProjectId, DwIdCdMaintenance::getProjectName));
        return map;
    }

*
     * 获取物料数据
     *
     * @param Ids Id集合
     * @return Map<Integer, String>
     * @date 2020-12-23 16:02:07
     * @author lyc


    public Map<String, String> getMaterielByIds(String Ids) {
        Map<String, String> Map = new HashMap<>();
        try {
            R<List<EpPmCatalogueDto>> r = catalogueService.selectByIds(Ids);
            List<EpPmCatalogueDto> data = r.getData();
            data.forEach(item -> {
                Map.put(String.valueOf(item.getCatalogueId()), item.getMaterielName());
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Map;
    }

*
     * 获取保养方式
     *
     * @return Map<Integer, String>
     * @date 2020-12-23 16:02:07
     * @author lyc


    public Map<Integer, String> getMaintenanceWay() {
        List<DwIdCdMaintenance> items = epEmMaintenanceService.findDwIdCdMaintenance(1);
        Map<Integer, String> map = items.stream().collect(Collectors.toMap(DwIdCdMaintenance::getProjectId, DwIdCdMaintenance::getProjectName));
        return map;
    }


*
     * 查询计划集合
     *
     * @param contentIds 内容Ids
     * @return List<EpEmMaintenancePlan>
     * @date 2020-12-23 16:02:07
     * @author lyc


    public List<EpEmMaintenancePlan> getPlansByContentIds(List<Integer> contentIds) {
        LambdaQueryWrapper<EpEmMaintenancePlan> planWapper = new LambdaQueryWrapper<>();
        planWapper.in(EpEmMaintenancePlan::getContentId, contentIds);
        return epEmMaintenancePlanDao.selectList(planWapper);
    }

*
     * 查询计划集合
     *
     * @param contentId 内容Ids
     * @return List<EpEmMaintenancePlan>
     * @date 2020-12-23 16:02:07
     * @author lyc


    private List<EpEmMaintenancePlan> getPlansByContentId(Integer... contentId) {
        LambdaQueryWrapper<EpEmMaintenancePlan> planWapper = new LambdaQueryWrapper<>();
        planWapper.in(EpEmMaintenancePlan::getContentId, Arrays.asList(contentId));
        return epEmMaintenancePlanDao.selectList(planWapper);
    }


*
     * 查询计划集合
     *
     * @param contentId 内容Ids
     * @return List<EpEmMaintenancePlan>
     * @date 2020-12-23 16:02:07
     * @author lyc


    private List<EpEmMaintenancePlan> getMonthPlansByContentId(Integer month, Integer... contentId) {
        return epEmMaintenancePlanDao.queryMonthByContentId(month, contentId);
    }


*
     * 处理维护信息为计划时间
     *
     * @param item 维护内容信息
     * @return Object
     * @date 2020年12月22日15:17:34
     * @author lyc


    private List<EpEmMaintenancePlan> doHandlePlan(EpEmMaintenanceContent item) {
        Integer projectId = item.getProjectId();
        EpEmMaintenancePorject project = this.getById(projectId);//项目信息
        String maintenancePeriod = item.getMaintenancePeriod(); //周期类型 0按月 1指定周 2指定月
        String periodType = item.getPeriodType(); //维护周期
        Integer contentId = item.getContentId();//维护内容Id
        Integer remindDay = item.getRemindDay(); //提前提醒日期
        int year = StringUtils.isBlank(project.getPlanYear()) ? LocalDate.now().getYear() : Integer.parseInt(project.getPlanYear());
        List<EpEmMaintenancePlan> items = new ArrayList<>();
        switch (maintenancePeriod) {
            case MaintenancePlanConstant.PERIODTYPE_MONTH: //按月
                int num = Integer.parseInt(periodType);
                for (int i = 1; i <= MaintenancePlanConstant.MONTH; i++) {
                    if (num == 1 || i % num == 1) {
                        Date beginTime = DateUtil.getBeginTimeByYM(year, i);
                        Date endTime = DateUtil.getEndTimeByYM(year, i);
                        Date beforeDay = DateUtil.getBeforeDay(beginTime, remindDay);
                        EpEmMaintenancePlan plan = new EpEmMaintenancePlan();
                        plan.setContentId(contentId);
                        plan.setRemindDay(beforeDay);
                        plan.setPlanStartTime(beginTime);
                        plan.setPlanEndTime(endTime);
                        items.add(plan);
                    }
                }
                break;
            case MaintenancePlanConstant.PERIODTYPE_ASSIGN_WEEK: //指定周
                String[] week = periodType.split(MaintenancePlanConstant.STR_SPLIT);
                List<Date> weekDay = DateUtil.getWeekDay(year, week);
                weekDay.forEach(date -> {
                    Date beginTime = DateUtil.getBeginTimeByDay(date);
                    Date endTime = DateUtil.getEndTimeByDay(date);
                    Date beforeDay = DateUtil.getBeforeDay(beginTime, remindDay);
                    EpEmMaintenancePlan plan = new EpEmMaintenancePlan();
                    plan.setContentId(contentId);
                    plan.setRemindDay(beforeDay);
                    plan.setPlanStartTime(beginTime);
                    plan.setPlanEndTime(endTime);
                    items.add(plan);
                });
                break;
            case MaintenancePlanConstant.PERIODTYPE_ASSIGN_MONTH:// 指定月
                String[] months = periodType.split(MaintenancePlanConstant.STR_SPLIT);
                for (String month : months) {
                    int assignMonth = Integer.parseInt(month);
                    if (assignMonth > MaintenancePlanConstant.MONTH)
                        continue;
                    Date beginTime = DateUtil.getBeginTimeByYM(year, assignMonth);
                    Date endTime = DateUtil.getEndTimeByYM(year, assignMonth);
                    Date beforeDay = DateUtil.getBeforeDay(beginTime, remindDay);
                    EpEmMaintenancePlan plan = new EpEmMaintenancePlan();
                    plan.setContentId(contentId);
                    plan.setRemindDay(beforeDay);
                    plan.setPlanStartTime(beginTime);
                    plan.setPlanEndTime(endTime);
                    items.add(plan);
                }
                break;
        }

        return items;
    }

*
     * 维护计划Id集合 获取内容集合
     *
     * @param Ids 维护计划Id集合
     * @return List<EpEmMaintenanceEquipment>
     * @date 2020年12月23日09:40:43
     * @author lyc


    public List<EpEmMaintenanceContent> getContentsByProjectIds(List<Integer> Ids) {
        LambdaQueryWrapper<EpEmMaintenanceContent> contentWrapper = new LambdaQueryWrapper<>();
        contentWrapper.in(EpEmMaintenanceContent::getProjectId, Ids).orderByAsc(EpEmMaintenanceContent::getProjectId, EpEmMaintenanceContent::getContentId);
        return epEmMaintenanceContentDao.selectList(contentWrapper);
    }

*
     * 维护计划Id集合 获取设备集合
     *
     * @param Ids 维护计划Id集合
     * @return List<EpEmMaintenanceEquipment>
     * @date 2020年12月23日09:40:43
     * @author lyc


    public List<EpEmMaintenanceEquipment> getEquipmentsByProjectIds(List<Integer> Ids) {
        LambdaQueryWrapper<EpEmMaintenanceEquipment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EpEmMaintenanceEquipment::getProjectId, Ids);
        return epEmMaintenanceEquipmentDao.selectList(queryWrapper);
    }

*
     * 通过维护计划Id 获取内容集合
     *
     * @param projectId 维护计划Id
     * @return List<EpEmMaintenanceEquipment>
     * @date 2020年12月23日09:40:43
     * @author lyc


    public List<EpEmMaintenanceContent> getContentsByProjectId(Integer projectId) {
        LambdaQueryWrapper<EpEmMaintenanceContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EpEmMaintenanceContent::getProjectId, projectId).orderByAsc(EpEmMaintenanceContent::getOrderId);
        return epEmMaintenanceContentDao.selectList(queryWrapper);
    }


*
     * 通过维护计划Id 获取设备集合
     *
     * @param projectId 维护计划Id
     * @return List<EpEmMaintenanceEquipment>
     * @date 2020年12月23日09:40:43
     * @author lyc


    public List<EpEmMaintenanceEquipment> getEquipmentsByProjectId(Integer projectId) {
        LambdaQueryWrapper<EpEmMaintenanceEquipment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EpEmMaintenanceEquipment::getProjectId, projectId);
        return epEmMaintenanceEquipmentDao.selectList(queryWrapper);
    }

*
     * 检查项目数据
     *
     * @param project 数据源
     * @param hasId   是否存在主键Id
     * @date 2020年12月22日15:17:34
     * @author lyc


    private void checkProject(EpEmMaintenancePorject project, boolean hasId) {
        try {
            if (project == null)
                throw new Exception("参数不能为空");
            if (project.getProjectName() == null)
                throw new Exception("项目名称不能为空");
            if (project.getOrganizationId() == null)
                throw new Exception("工厂组织信息不能为空");
            if (project.getOrderId() == null)
                throw new Exception("排序编号不能为空");
            if (hasId && project.getProjectId() == null)
                throw new Exception("维护计划ID不能为空");
            String year = StringUtils.isBlank(project.getPlanYear()) ? String.valueOf(LocalDate.now().getYear()) : project.getPlanYear();
            project.setPlanYear(year);
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }

    }

*
     * 检查维护内容数据
     *
     * @param bean  数据源
     * @param hasId 是否存在主键Id
     * @date 2020年12月22日15:17:34
     * @author lyc


    private void checkContent(EpEmMaintenanceContent bean, boolean hasId) {
        try {
            if (bean == null)
                throw new Exception("参数不能为空");
            if (bean.getProjectId() == null)
                throw new Exception("维护项目Id不能为空");
            if (bean.getDepartmentId() == null)
                throw new Exception("维护部门不能为空");
            if (bean.getProjectMethod() == null)
                throw new Exception("维护类型不能为空");
            if (bean.getMaintenancePeriod() == null)
                throw new Exception("周期类型不能为空");
            if (bean.getPeriodType() == null)
                throw new Exception("维护周期不能为空");
            if (bean.getHourEstimate() == null)
                throw new Exception("工时估算不能为空");
            if (bean.getRemindDay() == null)
                throw new Exception("提前通知不能为空");
            if (bean.getSavePicture() == null)
                throw new Exception("拍照记录不能为空");
            if (bean.getOrderId() == null)
                throw new Exception("排序序号不能为空");
            if (bean.getMaintenanceMethod() == null)
                throw new Exception("维护内容不能为空");
            if (hasId && bean.getContentId() == null)
                throw new Exception("维护内容ID不能为空");
            bean.setMaintenanceContent(bean.getMaintenanceMethod());
            bean.setCostEstimate(bean.getCostEstimate() == null ? 0d : bean.getCostEstimate());
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }
    }

*
     * 检查维护内容数据
     *
     * @param bean 数据源
     * @date 2020年12月22日15:17:34
     * @author lyc


    private void checkEquipment(EpEmMaintenanceEquipment bean) {
        try {
            if (bean == null)
                throw new Exception("参数不能为空");
            if (bean.getEquipmentId() == null)
                throw new Exception("设备不能为空");
            if (bean.getProjectId() == null)
                throw new Exception("维护项目ID不能为空");
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }
    }

*
     * 检查数据
     *
     * @param bean  数据源
     * @param hasId 是否存在主键Id
     * @date 2020年12月22日15:17:34
     * @author lyc


    private void check(MaintenancePlanDto bean, boolean hasId) {
        try {
            EpEmMaintenancePorject project;
            if (bean == null || (project = bean.getProject()) == null || bean.getContents() == null || bean.getEquipments() == null)
                throw new Exception("参数不能为空");
            if (bean.getContents().isEmpty())
                throw new Exception("维护内容不能为空");
            if (bean.getEquipments().isEmpty())
                throw new Exception("维护设备不能为空");
            if (project.getProjectName() == null)
                throw new Exception("项目名称不能为空");
            if (project.getOrganizationId() == null)
                throw new Exception("工厂组织信息不能为空");
            if (project.getPlanYear() == null)
                throw new Exception("计划年份不能为空");
            if (project.getOrderId() == null)
                throw new Exception("排序编号不能为空");
            if (hasId && project.getProjectId() == null)
                throw new Exception("维护计划ID不能为空");
        } catch (Exception e) {
            throw new ServerErrorException(e.getMessage(), e);
        }
    }
}
*/
